package com.ashin.context;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ashin.util.WebUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class MyTenantLineHandler implements TenantLineHandler {

    public static final String TENANT_ID_IDENTIFIER_HEADER_NAME = "current_account_tenant_code";

    public Expression getTenantId() {
        HttpServletRequest request = WebUtil.getRequest();
        if (request != null && StrUtil.isNotBlank((String) request.getAttribute(TenantIdContext.TENANTCODE_ATTRIBUTE))) {
            return new StringValue((String) request.getAttribute(TenantIdContext.TENANTCODE_ATTRIBUTE));

        } else {
            return request != null && StrUtil.isNotBlank(request.getHeader(TENANT_ID_IDENTIFIER_HEADER_NAME)) ?
                    new StringValue(request.getHeader(TENANT_ID_IDENTIFIER_HEADER_NAME)) : new StringValue(StrUtil.EMPTY);
        }
    }


    public boolean ignoreTable(String tableName) {
        List<String> ignoreDynTables = TenantIgnoreTableContext.getUserDefinedIgnoreTables();
        return CollUtil.isNotEmpty(ignoreDynTables) && ignoreDynTables.contains(tableName);
    }


}
